#!/bin/bash

VAR_DIR="./var"

# Make initial tasks 
if [ ! -d $VAR_DIR ] ; then
    mkdir $VAR_DIR
#    first_run
    cat /proc/stat > $VAR_DIR/stat
    cat /proc/net/dev > $VAR_DIR/net.dev
    cat /proc/diskstats > $VAR_DIR/diskstats
    echo "There is no var directory and no previos states"
    exit 1
fi

readarray STATp < $VAR_DIR/stat
readarray NETp < $VAR_DIR/net.dev
readarray DISKp < $VAR_DIR/diskstats

readarray STAT < /proc/stat
readarray NET < /proc/net/dev
readarray DISK < /proc/diskstats

echo "${STAT[*]}" > $VAR_DIR/stat
echo "${NET[*]}" > $VAR_DIR/net.dev
echo "${DISK[*]}" > $VAR_DIR/diskstats

#/bin/df | readarray DF 
#readarray MEMINFO < /proc/meminfo

CPU=(${STAT[0]})
CPUp=(${STATp[0]})

HelpTopic () {
printf "${STATp[0]}${STAT[0]}" |\
awk 'BEGIN {print "CPU usage:"}
{us=$2-us;ni=$3-ni;sy=$4-sy;id=$5-id;io=$6-io;ir=$7-ir;si=$8-si;st=$9-st;gu=$10-gu}
END {tot=(us+ni+sy+id+io+ir+si+st+gu)/100
printf "User:%8.1f %%\nNice:%8.1f %%\nSystem:%6.1f %%\nIdle:%8.1f %%\nIOwait:%6.1f %%\nIRQ:%9.1f %%\nSoftIRQ:%5.1f %%\nSteal:%7.1f %%\nGuest:%7.1f %%\n",us/tot,ni/tot,sy/tot,id/tot,io/tot,ir/tot,si/tot,st/tot,gu/tot}
'
}

show () {
#CPUt=0
for i in {1..9} ; do
    CPUd[$i]=$((${CPU[$i]}-${CPUp[$i]}))
    CPUt=$((${CPUt}+${CPUd[$i]}))
done
for i in User: Nice: System: Idle: IOwait: IRQ: SoftIRQ: Steal: Guest: ; do
n=$((++n))
VAL=$((${CPUd[$n]}*1000/${CPUt}))
printf "$i%2d%%\n" $VAL
# ${VAL: -3:1}${VAL: -2:1}.${VAL: -1}
done
}
case $1 in
    show) show ;;
    *) HelpTopic ;;
esac
